import io
from django.http import HttpResponse
from reportlab.pdfgen import canvas


def pdf_by_io(request):
    # 创建BytesIO实例。准备把文件写入内存
    buffer = io.BytesIO()

    # 创建canvas实例，指定写入对象为BytesIO实例
    p = canvas.Canvas(buffer)

    # 把指定文字写到指定位置
    p.drawString(50, 50, 'pdf by io page 1 line 1')
    p.drawString(50, 100, 'pdf by io page 1  line 2')
    p.drawString(100, 200, 'pdf by io page 1  line 3')

    # 会隐藏部分文字
    p.drawString(-10, -2, 'pdf by io page 1  line 4')
    # 结束当前页的编辑。并开始新一页的编辑
    p.showPage()

    p.drawString(50, 50, 'pdf by io page 2 line 1')
    p.drawString(500, 700, 'pdf by io page 2 line 2')

    s = ""
    for i in range(10000):
        s += str(i)
    # 写入超长文字会不显示超出部分
    p.drawString(500, 700, 'pdf by io page 2 line 2' + s)

    p.showPage()

    # 保存并关闭canvas对象
    p.save()

    # 取出BytesIO对象中写入的pdf文件内容
    pdf_content = buffer.getvalue()

    # 关闭BytesIO对象
    buffer.close()

    # 设定pdf文件下载专用的content_type
    response = HttpResponse(content_type='application/pdf')

    # 设定下载pdf文件的文件名
    response['Content-Disposition'] = 'attachment; filename="pdf_by_io.pdf"'

    # 把pdf文件的内容写入response
    response.write(pdf_content)
    return response


def pdf_by_response(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="pdf_by_res.pdf"'

    p = canvas.Canvas(response)
    # 把指定文字写到指定位置
    p.drawString(50, 50, 'pdf by io page 1 line 1')
    p.drawString(50, 100, 'pdf by io page 1  line 2')
    p.drawString(100, 200, 'pdf by io page 1  line 3')

    # 会隐藏部分文字
    p.drawString(-10, -2, 'pdf by io page 1  line 4')
    # 结束当前页的编辑。并开始新一页的编辑
    p.showPage()

    p.drawString(50, 50, 'pdf by io page 2 line 1')
    p.drawString(500, 700, 'pdf by io page 2 line 2')

    s = ""
    for i in range(10000):
        s += str(i)
    # 写入超长文字会不显示超出部分
    p.drawString(500, 700, 'pdf by io page 2 line 2' + s)

    p.showPage()

    # 保存并关闭canvas对象
    p.save()
    return response

